import ajaxAsync from 'vue-xiaobu-utils'
// import OrderInfoModel from '../models/OrderInfoModel'
import PayTypeModel from '../models/PayTypeModel'
import { open } from '@/utils/JumpUtils.js'

var test = false

/**
 * 获取扣款失败的行程列表
 * @param {Number} pageIndex
 * @param {Number} pageSize
 */
function getUnpayList(pageIndex, pageSize) {
  if (test) {
    return getTestOrderList().then(body => {
      // let list = body.LIST
      // let convertList = []
      // list.map(item => {
      //   convertList.push(new OrderInfoModel(item))
      // })
      // body.LIST = convertList
      return body
    })
  } else {
    let postData = {
      PAGE_INDEX: pageIndex,
      PAGE_CAPACITY: pageSize
    }
    return ajaxAsync('/posbill/unpaysuccess/list', postData)
  }
}

function getTestOrderList() {
  return new Promise((resolve, reject) => {
    let list = []
    for (let i = 0; i < 6; i++) {
      let orderInfo = {
        MONTH: '2019-0' + (i + 1),
        LIST: [
          {
            POS_BILL_NO: '212312-' + i + '-' + 1,
            PAY_PRICE: 2.0,
            RIDE_TIME: '2018-11-15',
            POS_BILL_TITLE: '标题'
          },
          {
            POS_BILL_NO: '212312-' + i + '-' + 2,
            PAY_PRICE: 2.0,
            RIDE_TIME: '2019-03-15',
            POS_BILL_TITLE: '标题'
          }
        ]
      }
      list.push(orderInfo)
    }
    let body = {
      COUNT: 12,
      LIST: list,
      AMOUNT: '20.8'
    }
    // return body
    setTimeout(() => {
      resolve(body)
    }, 200)
  })
}

/**
 * 获取支付方式列表
 * @param {String} amount 订单总金额
 */
async function getPayTypeList(amount) {
  let body = {}

  if (test) {
    // 测试数据
    let payList = [
      {
        paymentName: '支付宝',
        payment: 'ALIPAY',
        type: 4
      }
    ]
    for (let i = 1; i < 7; i++) {
      if (i === 6) {
        let payMap = {
          paymentName: '添加银行卡',
          payment: 'BINDCARD_PAY',
          type: 0
        }
        payList.push(payMap)
      } else {
        let type = [1, 2][Math.floor(Math.random() * 2)]
        let payMap
        if (type === 1) {
          payMap = {
            paymentName: '银行卡' + i,
            payment: 'BINDCARD_PAY',
            payAccount: 'card' + i,
            bankCardShortNo: '4657',
            type: type
          }
        } else {
          let walletBody = '0.00'
          let status = 0 // 状态STATUS：0.正常 1.已冻结 2.已注销，还会有其他状态，其他状态都显示为正常，新注册用户未开通会提示错误没有该卡，错误号：CARD100116
          payMap = {
            paymentName: '钱包余额',
            balance: walletBody,
            payment: 'ACCOUNT_PAY',
            payAccount: 'account' + i,
            type:
              status === 1 ? 5 : walletBody > 0 && walletBody >= amount ? 2 : 3,
            statusTips:
              status === 1
                ? window.buscardName + '已冻结'
                : walletBody > 0 && walletBody >= amount
                  ? ''
                  : '余额不足'
          }
        }
        payList.push(payMap)
      }
    }
    body.PAY_LIST = payList
    return body

    // body = await getPayTypeList()
  } else {
    // 协议请求
    body = await ajaxAsync('/payment/order', {})
    let walletBody = await ajaxAsync('/wallet/balance/get', {})

    let list = body.LIST
    let payList = [
      {
        paymentName: '支付宝',
        payment: 'ALIPAY',
        type: 4 // 支付宝
      }
    ]
    list.map((item, index) => {
      let payTypeModel
      // ACCOUNT_PAY:账户余额支付，BINDCARD_PAY：绑卡付（绑卡暂时不支持）
      if (item.PAYMENT === 'ACCOUNT_PAY') {
        item.BALANCE = walletBody.BALANCE
        item.STATUS = walletBody.STATUS
        if (item.STATUS === 1) {
          // 状态STATUS：0.正常 1.已冻结 2.已注销，还会有其他状态，其他状态都显示为正常，新注册用户未开通会提示错误没有该卡，错误号：CARD100116
          item.TYPE = 5 // 卡已冻结
          item.STATUS_TIPS = window.buscardName + '已冻结' // window.buscardName卡名称文案
          payTypeModel = new PayTypeModel(item)
        } else if (item.BALANCE > 0) {
          item.TYPE = 2 // 钱包余额可用
          payTypeModel = new PayTypeModel(item)
        } else {
          item.TYPE = 3 // 钱包余额不足
          item.STATUS_TIPS = '余额不足'
          payTypeModel = new PayTypeModel(item)
        }
        payList.push(payTypeModel)
      } else {
        // （window.isSupportUnionPay是否支持绑卡付，cityConfig中配置）
        if (window.isSupportUnionPay) {
          item.TYPE = 1 // 银联卡
          payTypeModel = new PayTypeModel(item)
          payList.push(payTypeModel)
        }
      }
    })
    // （window.isSupportUnionPay是否支持绑卡付，cityConfig中配置）
    if (window.isSupportUnionPay) {
      payList.push({
        paymentName: '添加银行卡',
        type: 0 // 添加银行卡
      })
    }
    body.PAY_LIST = payList
    return body
  }
}

/**
 * 支付失败行程账单
 * @param {Object} data 扣款协议请求参数
 */
async function payFailPosBill(data) {
  let body = {}

  if (test) {
    let list = {
      UNIFY_PAY_NO: '4465465465465142',
      PAYMENT_STR: 'gfsdgdfggdfgdfgfds'
    }
    body = list
    return body
  } else {
    body = await ajaxAsync('/posbill/unpaysuccess/pay', data)
    return body
  }
}

/**
 *
 * @param {String} price 订单金额
 * @param {String} unifyPayNo 支付流水号
 * @param {String} notifyUrl 回调地址
 */
function payFailPosBillCallback(price, unifyPayNo, notifyUrl) {
  if (notifyUrl.indexOf('xbapp://') < 0) {
    notifyUrl = 'xbapp://goback/buscard-app/' + notifyUrl + '.html'
  }
  open(
    'xbapp://open/buscard-app/payresult.html?_tv=false&price=' +
      encodeURIComponent(price) +
      '&unifyPayNo=' +
      encodeURIComponent(unifyPayNo) +
      '&notifyUrl=' +
      encodeURIComponent(notifyUrl)
  )
}

export { getUnpayList, getPayTypeList, payFailPosBill, payFailPosBillCallback }
